<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="商户" prop="mchId">
        <el-select v-model="queryParams.mchId" clearable filterable placeholder="请选择商户" size="small">
          <el-option
            v-for="dept in deptList"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="dept.deptId"
          >
            <span style="float: left">{{ dept.deptName }}</span>a
            <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入客户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户类型" prop="customerType">
        <el-select v-model="queryParams.customerType" placeholder="请选择客户类型" clearable>
          <el-option
            v-for="dict in dict.type.crm_customer_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级" prop="customerLevel">
        <el-select v-model="queryParams.customerLevel" placeholder="请选择客户等级" clearable>
          <el-option
            v-for="dict in dict.type.crm_customer_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属省" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入所属省"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入所属市"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入所属地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="习惯" prop="habit">
        <el-input
          v-model="queryParams.habit"
          placeholder="请输入习惯"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="客户来源" prop="source">
        <el-input
          v-model="queryParams.source"
          placeholder="请输入客户来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 335px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hrcrm:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hrcrm:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hrcrm:customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['hrcrm:customer:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hrcrm:customer:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-share"
          size="mini"
          @click="handleAllocation"
          v-hasPermi="['hrcrm:customer:allocation']"
        >分配</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户ID" align="center" prop="id" />
      <el-table-column label="商户" align="center" prop="mchId" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="dept in deptList">
            <span v-if="dept.deptId == scope.row.mchId">{{dept.deptName}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName" width="120" show-overflow-tooltip />
      <el-table-column label="客户昵称" align="center" prop="nickname" width="120" show-overflow-tooltip />
<!--      <el-table-column label="会员ID" align="center" prop="memberId" width="120" show-overflow-tooltip />-->
      <el-table-column label="公司名称" align="center" prop="companyName" width="120" show-overflow-tooltip />
      <el-table-column label="手机号" align="center" prop="phoneNumber" width="110" show-overflow-tooltip />
<!--      <el-table-column label="头像" align="center" prop="avatar" />-->
      <el-table-column label="客户类型" align="center" prop="customerType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_customer_type" :value="scope.row.customerType"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="职位" align="center" prop="position" />-->
      <el-table-column label="客户等级" align="center" prop="customerLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_customer_level" :value="scope.row.customerLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
<!--      <el-table-column label="所属省" align="center" prop="province" />
      <el-table-column label="所属市" align="center" prop="city" />-->
      <el-table-column label="所属地址" align="center" prop="address" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          {{scope.row.province}} &nbsp; {{scope.row.city}} &nbsp; {{scope.row.address}}
        </template>
      </el-table-column>
<!--      <el-table-column label="生日" align="center" prop="birthday" />-->
<!--      <el-table-column label="习惯" align="center" prop="habit" />-->
      <el-table-column label="客户来源" align="center" prop="source" width="120" show-overflow-tooltip />
      <el-table-column label="最后跟进时间" align="center" prop="lastContactTime" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastContactTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="lastContactTime" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户备注" align="center" prop="customerNote" width="80" show-overflow-tooltip />
<!--      <el-table-column label="备注" align="center" prop="remark" width="80" show-overflow-tooltip />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="toDetail(scope.row)"
            v-hasPermi="['hrcrm:customer:list']"
          >详情</el-button>

          <el-dropdown>
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['hrcrm:customer:edit']"
                >修改</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['hrcrm:customer:remove']"
                >删除</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="width: 95%; ">
        <el-form-item label="商户" prop="mchId">
          <el-select v-model="form.mchId" clearable filterable placeholder="请选择商户" size="small">
            <el-option
              v-for="dept in deptList"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptId"
            >
              <span style="float: left">{{ dept.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入客户昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="会员ID" prop="memberId">
          <el-input v-model="form.memberId" placeholder="如客户绑定已存在会员，请输入ID" />
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="16" :max="100" placeholder="请输入年龄" :controls="false" />
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select v-model="form.customerType" placeholder="请选择客户类型">
            <el-option
              v-for="dict in dict.type.crm_customer_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级" prop="customerLevel">
          <el-select v-model="form.customerLevel" placeholder="请选择客户等级">
            <el-option
              v-for="dict in dict.type.crm_customer_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属地址" prop="address">
          <el-cascader
            size="large"
            :options="pcaTextArr"
            v-model="addresses">
          </el-cascader>
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入客户来源" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="微信" prop="wx">
          <el-input v-model="form.wx" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="客户备注" prop="customerNote">
          <el-input v-model="form.customerNote" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户分配对话框 -->
    <el-dialog :title="allocation.title" :visible.sync="allocation.open" width="450px" append-to-body :close-on-click-modal="false">
      <el-form ref="allocationForm" :model="allocation.form" :rules="rules" label-width="100px" style="width: 95%; ">
        <el-form-item label="商户" prop="mchId">
          <el-select v-model="allocation.form.mchId" @change="toBeAllocation(allocation.form.mchId)" clearable filterable placeholder="请选择商户">
            <el-option
              v-for="dept in deptList"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptId"
            >
              <span style="float: left">{{ dept.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工" prop="employeeId">
          <el-select v-model="allocation.form.employeeId" clearable filterable placeholder="请选择员工">
            <el-option
              v-for="user in userList"
              :key="user.dictValue"
              :label="user.dictLabel"
              :value="user.dictValue"
            >
              <span style="float: left">{{ user.dictLabel }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.dictValue }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分配数量" prop="allocationNum">
          <el-input-number v-model="allocation.form.allocationNum" :min="0" :max="toBeAllocationCount" placeholder="请输入分配数量" :controls="false" />
        </el-form-item>
        <span v-if="toBeAllocationCount != null" style="margin-left: 90px">
          该商户下，未分配客户总数为：{{toBeAllocationCount}}
        </span>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllocationForm" :loading="buttonLoading">确 定</el-button>
        <el-button @click="allocation.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCustomer,
  getCustomer,
  delCustomer,
  addCustomer,
  updateCustomer,
  toBeAllocationCount, allocationCustomer
} from "@/api/hrcrm/customer";
import { pcaTextArr } from 'element-china-area-data'
import {allDept} from "@/api/system/dept";
import {getInfo} from "@/api/login";
import {getUserList} from "@/api/system/user";
import {upload} from "@/api/common";
import {getToken} from "@/utils/auth";

export default {
  name: "Customer",
  dicts: ['crm_customer_level', 'crm_customer_type', 'sys_user_sex', 'tf'],
  data() {
    return {
      // 遮罩层
      loading: true,
      buttonLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeLastContactTime: [],
      // 备注时间范围
      daterangeCreateTime: [],

      // 地址选择器开始
      pcaTextArr,
      addresses: [],
      // 地址选择器结束

      // 二级部门列表
      deptList: [],
      // 是否部门领导
      isLeader: true,
      // 是否管理员
      isAdmin: false,
      userParams: [],
      loginUserId: null,
      userList: [],

      toBeAllocationCount: null,
      upload: {
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 覆盖数据
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/hrcrm/customer/importData"
      },
      allocation: {
        open: false,
        title: '客户分配',
        form: {
          mchId: null,
          employeeId: null,
          allocationNum: null
        }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mchId: null,
        customerName: null,
        nickname: null,
        customerType: null,
        memberId: null,
        companyName: null,
        phoneNumber: null,
        customerLevel: null,
        gender: null,
        age: null,
        province: null,
        city: null,
        address: null,
        habit: null,
        source: null,
        lastContactTime: null,
        isFavorite: null,
        customerNote: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      importForm: {
        mchId: null,
        fileUrl: null
      },
      // 表单校验
      rules: {
        mchId: [
          { required: true, message: "商户ID不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        customerType: [
          { required: true, message: "客户类型不能为空", trigger: "change" }
        ],
        phoneNumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        // 客户分配验证开始
        employeeId: [
          { required: true, message: "员工不能为空", trigger: "change" }
        ],
        allocationNum: [
          { required: true, message: "分配数量不能为空", trigger: "change" },
          {
            validator: (rule, value, callBack) => {
              if(value <= 0){
                callBack('分配数量不能小于0')
              }else{
                callBack()
              }
            }
          }
        ],
        // 客户分配验证结束
      }
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getInfo().then(
        res => {
          if (!res.isAdmin && !res.isLeader) {
            this.isLeader = false;
          }
          if (res.isAdmin) {
            this.isAdmin = true;
          }
          //登录用户ID赋值
          this.loginUserId = res.user.userId;
          //拉取部门
          allDept().then(response => {
            this.deptList = response.data
            this.initUserList(this.deptList[0].deptId)
            if(!this.isAdmin){
              this.queryParams.mchId.push(this.deptList[0].deptId);
            }
            this.getList();
          });
        })
    },
    /** 选中部门的Id*/
    initUserList(deptId) {
      this.userList=[];
      this.userParams.deptId=deptId
      if(!this.isLeader){
        this.userParams.userId=this.loginUserId;
      }
      getUserList(this.userParams).then(response => {
        this.userList = response.data;
      });
    },
    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeLastContactTime && '' != this.daterangeLastContactTime) {
        this.queryParams.params["beginLastContactTime"] = this.daterangeLastContactTime[0];
        this.queryParams.params["endLastContactTime"] = this.daterangeLastContactTime[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mchId: null,
        customerName: null,
        nickname: null,
        avatar: null,
        customerType: "USER",
        memberId: null,
        companyName: null,
        position: null,
        phoneNumber: null,
        encryptedPhoneNumber: null,
        customerLevel: "A",
        gender: 0,
        age: null,
        province: null,
        city: null,
        address: null,
        birthday: null,
        habit: null,
        source: null,
        lastContactTime: null,
        isFavorite: null,
        wx: null,
        customerNote: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.addresses = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeLastContactTime = [];
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
        this.addresses.push(this.form.province, this.form.city, this.form.address)
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 地址处理start
          if (this.addresses != null && this.addresses.length > 0) {
            this.form.province = this.addresses[0]
            if (this.addresses[1] == "市辖区") {
              this.form.city = this.addresses[0]
            } else {
              this.form.city = this.addresses[1]
            }
            this.form.address = this.addresses[2]
          }
          // 地址处理end
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户信息编号为"' + ids + '"的数据项？').then(function() {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hrcrm/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    },
    /** 跳转至客户详情 */
    toDetail(row) {
      this.$router.push({path:'customer/detail',query: {id: row.id, mchId: row.mchId}})
    },

    /** 上传 */
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    importTemplate() {
      window.location.href = "/template/客户数据导入模板.xlsx";
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.open = true;
      this.title = "添加客户信息";
    },
    /** 取消 */
    importCancel() {
      this.upload.open = false;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 客户分配 start
    handleAllocation() {
      this.allocation.form.allocationNum = 1
      this.allocation.form.employeeId = null
      this.allocation.open = true;
      this.toBeAllocationCount = null;
    },
    // 客户分配
    submitAllocationForm() {
      this.$refs["allocationForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          let resultArr = this.userList.find((item) => {
            return item.dictValue == this.allocation.form.employeeId;
          });

          this.$modal.confirm('请确认，要给员工[' + resultArr.dictLabel + ']分配' + this.allocation.form.allocationNum + '条资源？')
            .then(function() {

            }).then(() => {
              allocationCustomer(this.allocation.form).then(response => {
                this.getList();
                this.$modal.msgSuccess("分配成功");
                this.allocation.open = false;
                this.buttonLoading = false;
              })
            }).catch(() => {
              this.allocation.open = false;
              this.buttonLoading = false;
            });
        }
      });
    },
    // 可分配客户总数
    toBeAllocation(mchId) {
      toBeAllocationCount(mchId).then(response => {
        this.toBeAllocationCount = response.data
      })
      this.initUserList(mchId)
    },
  }
};
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
</style>
